package com.software.frontend.searchmovie.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.software.frontend.R;
import com.software.frontend.searchmovie.utils.LoadingDialog;
import com.software.frontend.searchmovie.adapter.VideoAdapter;
import com.software.frontend.searchmovie.entity.Video;
import com.software.frontend.searchmovie.utils.DownloadUtil;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SearchMovieResultDetailActivity extends AppCompatActivity {

    private GridView gv_video;
    private SearchView sv_text;
    private Button btn_search, btn_save, btn_like;
    private ImageButton iBtn_return;
    private List<Video> videos;

    private SmartRefreshLayout refreshLayout;
    private int pageNum = 1;
    private int pageSize = 4;

    private String videoPath;
    private int movieId;
    private String searchStr;
    private String movieName;
    private VideoAdapter videoAdapter;
    private JCVideoPlayerStandard jcVideoPlayerStandard;
    private Dialog dialog;
    private String sessionId;
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            switch (msg.what){
                case 1:
                    //绑定适配器
                    jcVideoPlayerStandard.setUp(videos.get(0).getPath(),JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL,videos.get(0).getTranslatedContent());
                    videoPath = videos.get(0).getPath();
                    jcVideoPlayerStandard.startVideo();
                    videoAdapter = new VideoAdapter(SearchMovieResultDetailActivity.this, videos, R.layout.item_gridview_search_movie_result_detail);
                    gv_video.setAdapter(videoAdapter);
                    dialog.dismiss();//数据加载完成取消弹窗
                    break;
                case 2:
                    videoAdapter.notifyDataSetChanged();
                    refreshLayout.finishLoadMore();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_movie_result_detail);
        //初始化控件对象
        getViews();
        //获取搜索字符串
        Intent intent = getIntent();
        movieId = intent.getIntExtra("movieId",0);
        searchStr = intent.getStringExtra("searchStr");
        sessionId = intent.getStringExtra("sessionId");
        sv_text.setQuery(searchStr, false);
        //设置点击事件监听器
        setLintener();
        //加载弹窗
        LoadingDialog.Builder loadBuilder = new LoadingDialog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true)//返回键是否可点击
                .setCancelOutside(false);//窗体外是否可点击
        dialog = loadBuilder.create();
        dialog.show();//显示弹窗
        //从服务器端获取数据
        initData();

    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()){
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }


    private void initData() {
        //向服务发送异步的GET请求
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(getString(R.string.localhost) + "searchMovie/findByMovieId?id=" + movieId + "&pageNum=" + pageNum + "&pageSize=" + pageSize)
                .addHeader("cookie", sessionId)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                dialog.dismiss();
                Looper.prepare();
                Toast.makeText(SearchMovieResultDetailActivity.this, "请求出错啦！请重试！", Toast.LENGTH_SHORT).show();
                Looper.loop();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonStr = response.body().string();
                Log.e("abcd",jsonStr);
                Type type = new TypeToken<List<Video>>(){}.getType();
                if (pageNum == 1){
                    videos = new Gson().fromJson(jsonStr,type);
                    Message msg = new Message();
                    msg.what = 1;
                    myHandler.sendMessage(msg);
                }else {
                    List<Video> list = new Gson().fromJson(jsonStr,type);
                    videos.addAll(list);
                    Message msg = new Message();
                    msg.what = 2;
                    myHandler.sendMessage(msg);
                }
            }
        });
//        //初始化电影片段数据
//        videos = new ArrayList<>();
//        Video video1 = new Video();
//        video1.setId(1);
//        video1.setMovieId(1);
//        video1.setPath("https://klxxcdn.oss-cn-hangzhou.aliyuncs.com/histudy/hrm/media/bg1.mp4");
//        video1.setDuration(12);
//        video1.setTranslatedContent("我爱你");
//        videos.add(video1);
//
//        Video video2 = new Video();
//        video2.setId(2);
//        video2.setMovieId(1);
//        video2.setPath("https://klxxcdn.oss-cn-hangzhou.aliyuncs.com/histudy/hrm/media/bg2.mp4");
//        video2.setDuration(8);
//        video2.setTranslatedContent("我爱死你");
//        videos.add(video2);
//
//        Video video3 = new Video();
//        video3.setId(3);
//        video3.setMovieId(1);
//        video3.setPath("https://klxxcdn.oss-cn-hangzhou.aliyuncs.com/histudy/hrm/media/bg3.mp4");
//        video3.setDuration(30);
//        video3.setTranslatedContent("为什么我爱你");
//        videos.add(video3);
//
//        Video video4 = new Video();
//        video4.setId(4);
//        video4.setMovieId(1);
//        video4.setPath("https://stream7.iqilu.com/10339/upload_transcode/202002/17/20200217104524H4D6lmByOe.mp4");
//        video4.setDuration(25);
//        video4.setTranslatedContent("我不爱你哈哈");
//        videos.add(video4);
//
//        Video video5 = new Video();
//        video5.setId(5);
//        video5.setMovieId(1);
//        video5.setPath("http://stream4.iqilu.com/ksd/video/2020/02/17/87d03387a05a0e8aa87370fb4c903133.mp4");
//        video5.setDuration(11);
//        video5.setTranslatedContent("我真的不爱你哈哈");
//        videos.add(video5);
//
//        Video video6 = new Video();
//        video6.setId(6);
//        video6.setMovieId(6);
//        video6.setPath("http://rna5ai3pz.hb-bkt.clouddn.com/video/778c5884fa97f460dac8d90493c451de.mp4");
//        video6.setDuration(11);
//        video6.setTranslatedContent("我真的不爱你哈哈");
//        videos.add(video6);
    }

    private void setLintener() {
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SearchMovieResultDetailActivity.this, SearchMovieResultActivity.class);
                String str = sv_text.getQuery().toString();
                intent.putExtra("searchStr", str);
                startActivity(intent);
                finish();
            }
        });

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadUtil.downMp4(SearchMovieResultDetailActivity.this, videoPath);
            }
        });

        iBtn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        gv_video.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                jcVideoPlayerStandard.setUp(videos.get(i).getPath(),JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL,videos.get(i).getTranslatedContent());
                videoPath = videos.get(i).getPath();
                jcVideoPlayerStandard.startVideo();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //上拉加载更多时回调，此时去请求更多的数据
                pageNum++;//页码加1
                initData();
            }
        });
    }

    private void getViews() {
        btn_save = findViewById(R.id.btn_save);
        btn_like = findViewById(R.id.btn_like);
        btn_search = findViewById(R.id.search_movie_request_btn_search);
        iBtn_return = findViewById(R.id.search_movie_request_btn_return);
        sv_text = findViewById(R.id.search_movie_request_search_view);
        gv_video = findViewById(R.id.gv_video);
        jcVideoPlayerStandard= (JCVideoPlayerStandard) findViewById(R.id.jiecao_Player);
        refreshLayout = findViewById(R.id.refreshLayout);
    }
}